package com.thejoyrun.retrofit.http;

import com.thejoyrun.retrofit.utils.AssestsReader;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by kkmike999 on 2016/05/08.
 *
 * 模拟网络数据，短路网络请求。拦截request，直接返回response
 */
public class MockServerInterceptor implements Interceptor {

	private Map<String, String> pathMap = new HashMap<>();

	@Override
	public Response intercept(Chain chain) throws IOException {
		Request request = chain.request();

		String url = request.url()
		                    .url()
		                    .getPath();

		if (!pathMap.containsKey(url)) {
			RuntimeException throwable = new RuntimeException("url:[" + url + "] 未配置mock数据路径");
			throwable.printStackTrace();
			throw throwable;
		}

		String path = pathMap.get(url);

		// 模拟网络数据
		String content = AssestsReader.readFile(path);

		ResponseBody body = ResponseBody.create(MediaType.parse("application/x-www-form-urlencoded"), content);

		Response response = new Response.Builder().request(chain.request())
		                                          .protocol(Protocol.HTTP_1_1)
		                                          .code(200)
		                                          .body(body)
		                                          .build();
		return response;
	}

	public void setPath(String url, String localPath) {
		pathMap.put(url, localPath);
	}
}